# 用SVM加灰度共生矩阵提取的特征，训练后对数据进行分类（神经网络前的数据预处理）
# 已证实可行（20X放大倍数下）

from skimage import feature
from sklearn.decomposition import PCA
from PIL import Image
from pylab import *
import os, shutil
from libsvm.python.svmutil import *
from src.preprocessing.feature.feature_extraction import *


def train_model(feature_txt_path, options = '-c 32768.0 -g 0.0001 -b 0', copies = 1):
    # 提取特征和标签
    y, x = svm_read_problem(feature_txt_path)  # 读入训练文件

    # 提取部分特征
    if copies != 1:
        part_x = []
        part_y = []
        image_num = len(y)
        single_degree_image_num = int(image_num/4)
        # part_num = int(single_degree_image_num * copies)

        start_point = 0
        end_point = 0
        for i in range(4):
            start_point = i*single_degree_image_num
            i += 1
            end_point = int((i-1+copies) * single_degree_image_num)
            part_x.extend(x[start_point:end_point])
            part_y.extend(y[start_point:end_point])

    m = svm_train(part_y, part_x, options)   # 正式训练模型
    return m

'''
kind : 分类那一个等级特征的图像（1234对应着g0,g1,g2,g3等级）
model: 模型文件
options: 参数（不知道选1还是0）这里选0，原来他们做的是1
classify_img_path: 要分类的图像路径
classify_img_feature_path: 要分类的图像所提取的特征
transfer_img_path: 符合条件的图片转移到的目录
'''
def classify_image(classify_img_path, classify_feature_path, transfer_img_path, kind, model, options='-b 0'):
    # #..................................（实际图像处理）.......................................
    # 测试集提取特征为一个txt文件
    create_glcm_txt_for_classifying(classify_img_path, classify_feature_path, kind)

    # 处理要预测文件夹中的图片
    y, x = svm_read_problem(classify_feature_path)
    # 输出单张图片预测情况
    length = len(open(classify_feature_path, 'rU').readlines())
    print(length)
    image_num = []  # 存储图片序号

    for i in range(0, length, 1):
        # p_lable, p_acc, p_val = svm_predict(y2[i:i + 1], x2[i:i + 1], m, options='-b 1')
        p_lable, p_acc, p_val = svm_predict(y[i:i + 1], x[i:i + 1], model, options=options)
        if p_lable[0] == kind:
            image_num.append(i)

    print(len(image_num))

    file_num = 0

    # shutil.copy('C:\\spam.txt', 'C:\\delicious')

    for files in os.listdir(classify_img_path):
        # 将预测结果为normal的图片移动到normal文件夹
        if file_num in image_num:
            # os.remove(path_positive + files)
            # 这里是复制满足要求的图片到新的路径
            shutil.copy(classify_img_path + files,
                        transfer_img_path)

        file_num = file_num + 1

    # ............................................................................


if __name__ == '__main__':
    Her2_feature_10X_all_path = '../../../data/txt/feature/glcm_10X_all.txt'
    model = train_model(Her2_feature_10X_all_path,copies=0.03)

    test_path = '../../../data/txt/feature/glcm_10X_all.txt'
    y_test, x_test = svm_read_problem(test_path)
    p_lable, p_acc, p_val = svm_predict(y_test, x_test, model, options='-b 0')
